package com.jxx.algorithm.datastructure;

import org.w3c.dom.Node;

/**
 * @author LitchiShell
 * @description:
 * @create 2021-11-16
 */
public class MyLinkedList {
    // 头节点指针
    private Node head;
    // 尾节点指针
    private Node last;
    // 链表实际长度
    private int size;

    /**
     * 链表插入元素
     * @param data 插入元素
     * @param index 插入位置
     */
    public void insert(int data, int index) {
        if (index < 0 || index > size) {
            throw new IndexOutOfBoundsException("超出链表节点范围！");
        }
        Node insertNode = new Node(data);
        if (size == 0) {
            // 空链表
            head = insertNode;
            last = insertNode;
        } else if(index == 0) {
            // 插入头部
            insertNode.next = head;
            head = insertNode;
        } else if(size == index) {
            // 插入尾部
            last.next = insertNode;
            last = insertNode;
        } else {
            // 插入中间
            Node prevNode = get(index);
            insertNode.next = prevNode.next;
            prevNode.next = insertNode;
        }
        size++;
    }

    /**
     * 链表查询元素
     * @param index 查找元素位置
     * @return
     */
    public Node get(int index) {
        if (index < 0 || index >= size) {
            throw new IndexOutOfBoundsException("超出链表节点范围！");
        }
        Node temp = head;
        for(int i = 0; i < index; i++) {
            temp = temp.next;
        }
        return temp;
    }

    /**
     * 删除链表元素
     * @param index 删除位置
     * @return
     */
    public Node remove(int index) {
        if (index < 0 || index >= size) {
            throw new IndexOutOfBoundsException("超出链表节点范围！");
        }
        Node removeNode = null;
        if (index == 0) {
            // 删除头节点
            removeNode = head;
            head = head.next;
        } else if (index == size - 1) {
            // 删除尾节点
            Node prevNode = get(index - 1);
            removeNode = prevNode.next;
            prevNode.next = null;
            last = prevNode;
        } else {
            // 删除中间节点
            Node prevNode = get(index - 1);
            removeNode = prevNode.next;
            Node nextNode = prevNode.next.next;
            prevNode.next = nextNode;
        }
        size--;
        return removeNode;

    }

    /**
     * 输出链表
     */
    public void output() {
        Node temp = head;
        while(temp!=null) {
            System.out.println(temp.data);
            temp = temp.next;
        }
    }

     private static class Node {

        int data;

        Node next;

        public Node(int data) {
            this.data = data;
        }
    }

    public static void main(String[] args) {
        MyLinkedList myLinkedList = new MyLinkedList();
        myLinkedList.insert(1,0);
        myLinkedList.insert(2,1);
        myLinkedList.insert(3,2);
        myLinkedList.insert(4,3);
        myLinkedList.insert(5,1);
        myLinkedList.remove(0);
        myLinkedList.output();
    }
}

